package com.api.controller;


import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.api.entity.Result;
import com.api.entity.RoleModules;
import com.api.service.RoleModulesService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@Api("角色 和 资源")
/* @RequestMapping("/roleModules") */
@ApiIgnore
public class RoleModulesController {

	@Autowired
	private RoleModulesService roleModulesService;
	@ApiOperation("获取指定角色能够访问的功能模块数据")
	@PostMapping("/GetModulesByRoleIdLayUI")
	public Object findAllByRid(@ApiParam("角色id")@RequestParam("roleId") String roleId,HttpServletRequest request,@ApiParam("Token 密钥")@RequestParam("token") String token) {
		
		String sessionToken = (String) request.getSession().getAttribute("token");
		if(sessionToken==""||sessionToken==null) {
			Result result = new Result("您的Token已过期，请重新获取并登录",0,false);
			return result;
		}else if(sessionToken.equals(token)) {
			return roleModulesService.loadTree(roleId);
		}else {
			Result result = new Result("请核实 Token 是否正确","",false);
			return result;
		}
	}
	@ApiOperation("保存指定的角色能够访问的所有功能模块到系统中")
	@PostMapping("/SetSysRights")
	public Object SetSysRights(@ApiParam("角色id")@RequestParam("rId") String rId,@ApiParam("模块id")@RequestParam("parentIds") String parentIds,HttpServletRequest request,@ApiParam("Token 密钥")@RequestParam("token") String token) {
		
		String sessionToken = (String) request.getSession().getAttribute("token");
		if(sessionToken==""||sessionToken==null) {
			Result result = new Result("您的Token已过期，请重新获取并登录",0,false);
			return result;
		}else if(sessionToken.equals(token)) {
			// 1.先清空该用户下的所有模块，防止发生重复的模块
			roleModulesService.deleteRoleModulesByRid(rId);
			// 2.则清空	
			int o = 0;
				for (String string : parentIds.split(",")) {
					RoleModules  rms = new RoleModules();
					rms.setMid(string);
					rms.setRoleId(rId);
					o += roleModulesService.addRoleModules(rms);
				}
				int b = parentIds.split(",").length;
				//System.out.println(b);
				//System.out.println(o);
				if(o == b) {
					Result result = new Result("操作成功","",true);
					return result;
				}else {
					Result result = new Result("操作失败","",false);
					return result;
				}
		}else {
			Result result = new Result("请核实 Token 是否正确","",false);
			return result;
		}
	}
	
	
	
}
